#!C:\Python25\python.exe

import os
import sys
import cgi
from datetime import datetime
import ConfigParser
import repository.SyntaxParser as sp
import repository.SQLGenerator2 as sg2
import repository.conn as co
import repository.condition
import repository.answer
import repository.patientCondition
import repository.Result as rs
import repository.Results as rss
import repository.template_parser as tp
import repository.result_parser
import repository.notesretrieve as nt
import repository.reportoutput as ro
import repository.notes_parser as nop
import repository.hofunctions as hof
from repository.DatabaseConnector import leaves


starttime = datetime.now()
cfg = ConfigParser.ConfigParser()
cfg.read("path.cfg")
templatepath = cfg.get("template", "path")
reportpath = cfg.get("report", "path")
resultpath = cfg.get("result", "path")


if ro.form.getvalue("template") is None:
   ro.xml2output()
else:
   
   print "Content-Type: text/html\n\n"
   #------------------------------------------------
   comparands = [">",">=","<","<=","=","<>"]
   types = ["and", "or"]
   ref_fns = ["all values", "any value", "last value"] # yet to implement last value
   stat_fns = ["mean", "sd", "median", "max", "min", "range", "mode", "sum", "count"] # yet to implement sum and count
   time_entities = ["hours", "days", "weeks"]
   keywords = [" whose ", " with ", " have ", " during ", " in "]
   
   #-------------------------------------------------
   
   template = str(ro.form.getvalue("template"))
   templatefilename = templatepath + template + ".xml"
   mrn = ro.form.getvalue("MRN")
   bedno = ro.form.getvalue("bedno")
   
     
   templateparser = tp.template_parser(templatefilename)

   patient = templateparser.get_patient(mrn)         
   cond = templateparser.get_cond(bedno)
   toc = templateparser.get_toc()
   db = templateparser.get_db()
   diagnosis = templateparser.get_diagnosis()
   time_val = templateparser.get_time_value()
   time_ent = templateparser.get_time_ent()
   ward = templateparser.get_ward()
   answer = templateparser.get_answer()
   #print answer
   #print cond
     
   duration = sp.toHours(time_val, time_ent)
   if duration > 48:
      real_time_val = 48 # use in realtime
   else:
      real_time_val = time_val
             
   results = rss.Results([],[],[])
      
   ##Load the eventslist and load all the dictionaries. configure all the exception   
   events = hof.BuildEventDict('dict/events.txt')
   for event in events:
      if events[event]['dictionary'] is not None:
         events[event]['dictionary'] = sp.buildHash(events[event]['path'])
         #print events[event]['dictionary']
         #print "<HR><HR>"
      else:
         events[event]['dictionary'] = sp.buildCategoricArray(events[event]['path'])
      
      if events[event]['answers'] is not None:
         events[event]['answers'] = sp.getAnswers(answer, ref_fns, stat_fns, events[event]['dictionary'])

      if events[event]['conditions'] is not None:
         events[event]['conditions'] = sp.getConditionArray(cond, comparands, types, events[event]['dictionary'])
      
   patient_conditions = sp.getConditions(patient, comparands, types, events['patientevents']['dictionary'], 'T')
   events['patientevents']['conditions'] = sp.transform_Conditions(patient_conditions, "realtime")
   
   SQL = sg2.SQLGenerator2('SNOMED','GICU',events['groupevents']['answers'],events['patientevents']['answers'],\
                                     events['adtevents']['answers'],events['drugevents']['answers'],events['chartevents']['answers'],events['medevents']['answers'],\
                                     events['labevents']['answers'],events['patientevents']['conditions'],events['adtevents']['conditions'],\
                                     events['chartevents']['conditions'],events['medevents']['conditions'],events['labevents']['conditions'],\
                                     None, real_time_val, time_ent, ward, events['categoric_terms']['dictionary'])
   
   resultsArray = [] # array of results
   logicalArray = [] # array of logical operator
   result_set = [] # final set of results
   
   patients = None
   
   #append patients satisfying demographic info to the results array
   if patient_conditions is not None:
       patientQuery = SQL.getPatientEvent()
       patients = co.toGICU(patientQuery)
   
   for event in events:
      if events[event]['conditions'] is not None and event != "patientevents":
         for condition in events[event]['conditions']:
            logicalArray.append(condition.getType())
            subQuery = SQL.generateSingleQuery(condition, events[event]['name'])
            res = co.toGICU(subQuery)
            resultsArray.append(res)
   
   finalResultArray = sp.getFinalResult(patients, resultsArray, logicalArray)
   
   cont = 1
   if finalResultArray is None:
      # if none, then there is no conditions, so retrieve all records in db
      cont = 1
      
   elif len(finalResultArray) == 0:
      # if length = 0, then there is no patient that satisfy all condition,s so retur nothing
      cont = -1
   
   if cont == 1:
      for event in events:
         if events[event]['answers'] is not None:
            for ind in range(0,len(events[event]['answers'])):
               query_realtime = SQL.generateFinalQuery(events[event]['name'], finalResultArray, ind)
               if events[event]['name'] == "patientevents" or events[event]['name'] == "adtevents":
                  querytype = 1
               elif events[event]['name'] == "groupevents" :
                  querytype = 4
               else:
                  querytype = 3
               print query_realtime
               res_realtime = co.toGICU(query_realtime,querytype)
               # creating a Result Object
               result = rs.Result(events[event]['answers'][ind].getVariable(),events[event]['name'],res_realtime,events[event]['answers'][ind].getStat_fn(),events[event]['answers'][ind].getRef_fn())
               # Append Result object to Results
               results.AppendRealtime(result)
      
   results.setFinalResult(results.getRealtimeResult())
   #CDAL query Result
   final_result = results.getFinalResult()
   
   #Notes retrieve result and notes parser
   notes = nt.notes_retrieve(1515944) #94711
   np = nop.notes_parser(notes)   

   #report out
   ro.template2output(templatefilename, events, final_result, np)
   #ro.template2output("template.xml/GICU_template.xml", None,[], np)

   endtime = datetime.now()
   duration = endtime - starttime
   print str(duration) + " was spent on this report generation!"
